(function() {
    'use strict';
    /**
     * @ngdoc function
     * @name webApp.controller:OrderCtrl
     * @description
     * # OrderCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('OrderCtrl', OrderCtrl);

    OrderCtrl.$inject = ['$scope', 'dataService', '$location', '$state', 'helper', '$rootScope', '$timeout', 'sessionService', 'cacheService', 'Upload', 'ERP_CONFIG'];

    function OrderCtrl($scope, dataService, $location, $state, helper, $rootScope, $timeout, sessionService, cacheService, Upload, ERP_CONFIG) {
        $scope.Event = {
            1: "E_ORDER_CANCEL", // 订单作废
            2: "E_ORDER_PAYMENT", // 订单支付
            3: "E_ORDER_CONFIRM", // 订单确认
            4: "E_ORDER_DELIVERY", // 订单发货
            5: "E_ORDER_RECEIVE", // 订单收货
            6: "E_ORDER_RATED", // 订单评价         
        };

        //显示 
        $scope.listAction = function() {
            $scope.pageSize = 10;
            $scope.idtype = 1;
            $scope.orlist = [];
            $scope.chosedStatus = "S_ORDER_WAIT_CONFIRM";

            $scope.getorderList();
            $scope.$on('event:up-store-id', function() {
                $scope.store_id = $rootScope.store_id;
                $scope.getorderList();
            });

            //监控选中
            $scope.$watch('fhmoder', function(newValue, oldValue) {
                if (newValue) {
                    var order_ids = [];
                    for (var i in newValue) {
                        order_ids.push(newValue[i].order_id);
                    }
                    $scope.selectedOrderIds = order_ids.join("\n");
                }
            }, true);
        }

        $scope.refund = function($event, fee) {
            if ($scope.order.status !== 'S_ORDER_WAIT_RECEIVE' && $scope.order.status !== 'S_ORDER_WAIT_DELIVERY' && $scope.order.status !== 'S_ORDER_WAIT_RECEIVE' && $scope.order.status !== 'S_ORDER_WAIT_RATE') {
                helper.myConfirm('您确认退款吗？', function() {
                    dataService.refundAdd({
                        'order_id': $scope.order.order_id,
                        "fee": fee
                    }).then(function(one) {
                        if (!one.Msg) {
                            $scope.ordergetone($scope.order.order_id);
                            helper.myTip("退款操作成功！", $event.currentTarget);
                        } else {
                            // $scope.statusup( $scope.order.order_id,);
                            helper.myTip("退款操作失败！" + one.Msg, $event.currentTarget);
                        }
                    });
                });
            }
        }

        $scope.service = function($event) {
            helper.myConfirm('您确认发起售后吗？', function() {
                dataService.serviceUpdate({
                    'order_id': $scope.order.order_id
                }).then(function(one) {
                    if (!one.Msg) {
                        $scope.ordergetone($scope.order.order_id)
                        helper.myTip("申请售后操作成功！", $event.currentTarget);
                    } else {
                        // $scope.statusup( $scope.order.order_id,);
                        helper.myTip("申请售后操作失败！" + one.Msg, $event.currentTarget);
                    }
                });
            });
        }

        //获取列表
        $scope.getorderList = function(pageNo) {
            $scope.industryCode = $rootScope.industryCode;
            var query = {};
            $scope.fhmoder = [];
            var key = $rootScope.store_id + "OrderCtrl";
            var cache = cacheService.get(key);
            if (!cache || pageNo) {
                query = {
                    page_no: pageNo,
                    page_size: $scope.pageSize,
                    query: {}
                };
                // 创建时间
                if ($scope.start_created && $scope.end_created) {
                    query.start_created = $scope.start_created;
                    query.end_created = $scope.end_created;
                }
                if ($scope.order_id) {
                    query.query.order_id = $scope.order_id;
                }
                //门店
                if ($scope.store_id) {
                    query.query.store_id = $scope.store_id;
                }
                if ($scope.chosedStatus && $scope.chosedStatus !== "All") {
                    query.query.status = $scope.chosedStatus;
                }
                //发货点id
                if ($scope.pickpoint_id > 0) {
                    query.query.pickpoint_id = $scope.pickpoint_id;
                }
                if ($scope.member_id) {
                    query.query.member_id = $scope.member_id;
                }
                if ($scope.deliver_name) {
                    query.query.deliver_name = $scope.deliver_name;
                }
                if ($scope.deliver_phone) {
                    query.query.deliver_phone = $scope.deliver_phone;
                }
                cacheService.set(key, query);
            } else {
                query = clone(cache);
                $scope.queryRcache(query);
            }

            $scope.orderslist = [];
            $scope.ordersTotal = 0;

            dataService.orderGet(query).then(function(list) {
                $timeout(function() {
                    if (list) {
                        list.orders.map(function(order) {
                            order.fuhao = $scope.huobi(order.app_id)
                        })
                        $scope.orderslist = list.orders;
                        $scope.ordersTotal = list.total_count;
                    }
                });
            });
        }

        $scope.queryRcache = function(query) {
            $scope.pageNo = query.page_no;
            $scope.page_size = query.page_size;
            if (query.query.pickpoint_id) {
                $scope.pickpoint_id = query.query.pickpoint_id;
            }

            if (!query.query.status) {
                $scope.chosedStatus = 'All';
            }

            if (query.query.store_id) {
                $scope.store_id = query.query.store_id;
            }

            if (query.query.order_id) {
                $scope.order_id = query.query.order_id;
            }

            if (query.start_created) {
                $scope.start_created = query.start_created;
            }

            if (query.end_created) {
                $scope.end_created = query.end_created;
            }

            if (query.query.status) {
                $scope.chosedStatus = query.query.status;
            }

            if (query.query.deliver_name) {
                $scope.deliver_name = query.query.deliver_name;
            }

            if (query.query.deliver_phone) {
                $scope.deliver_phone = query.query.deliver_phone;
            }
        }

        //批量发货
        $scope.pilianPost = function($event, type) {
            if ($scope.fhmoder) {
                var tt;
                if (type == 1) {
                    tt = "选中的订单确认全部执行推送订单？！"
                }
                if (type == 2) {
                    tt = "选中的订单确认全部执行推送支付单？"
                }
                helper.myConfirm(tt, function() {
                    var msg;
                    async.mapSeries($scope.fhmoder, function(data, callback) {
                        if (data) {
                            if (msg) {
                                //console.error("msg", msg);
                                callback(msg);
                            } else {
                                //批量订单
                                if (type == 1) {
                                    $scope.postOrder(data.order_id, type, 1).then(function(r) {
                                        //console.error("Msg-----------------", r);
                                        if (r.Msg) {
                                            msg = r.Msg;
                                        }
                                        callback(null);
                                    });
                                }
                                // 批量支付单
                                if (type == 2) {
                                    $scope.postPay(data.order_id, type).then(function(r) {
                                        if (r.Msg) {
                                            msg = r.Msg;
                                        }
                                        callback(null);
                                    });
                                }
                            }
                        } else {
                            callback(null);
                        }
                    }, function(e, r) {
                        //console.error("//////////////////////////////", e, r, msg);
                        if (msg) {
                            helper.message(msg, "error");
                        } else {
                            helper.myAlert("success", null, null, function() {
                                $scope.getorderList();
                            });
                        }
                    });
                });
            }
        }

        //批量发货
        $scope.pilianfh = function($event, status, type) {
            if ($scope.fhmoder) {
                var tt;
                if (type == 2) {
                    tt = "选中的订单确认全部执行批量无物流发货？"
                }
                if (type == 1) {
                    tt = "选中的订单确认全部执行批量订单确认！订单中包含的未成团的拼团订单也一并确认！"
                }

                helper.myConfirm(tt, function() {
                    helper.myTip("操作中,请勿操作!", $event.currentTarget, null, 5);
                    var dd = 0;
                    async.map($scope.fhmoder, function(data, callback) {
                        if (data) {
                            // 批量发货
                            if (status == 2) {
                                $scope.order = clone(data);
                                $scope.order.shipping_code = 0;
                                $scope.order.shipping_corp = 'SJWL';
                                $scope.savefh().then(function(r) {
                                    callback(null);
                                });
                            }
                            //批量确认
                            if (status == 1) {
                                $scope.statusup(data.order_id, 3, null, data, 1).then(function(r) {
                                    callback(null);
                                });
                            }
                            // //console.error("$scope.fhmoder", data);
                        } else {
                            callback(null);
                        }
                    }, function(e, r) {
                        helper.myAlert("success", null, null, function() {
                            $scope.getorderList();
                        });
                    });
                });
            }
        }

        //修改
        $scope.saveupdate = function(data) {
            if (data) {
                var order = {
                    order_id: $scope.order.order_id
                };
                if (data.province) {
                    order.province = data.province;
                }
                if (data.city) {
                    order.city = data.city;
                }
                if (data.district) {
                    order.district = data.district;
                }
                if (data.deliver_address) {
                    order.deliver_address = data.deliver_address;
                }
                if (data.deliver_name) {
                    order.deliver_name = data.deliver_name;
                }
                if (data.deliver_phone) {
                    order.deliver_phone = data.deliver_phone;
                }
                if (data.remark) {
                    order.remark = data.remark;
                }
                dataService.orderUpdate(order).then(function(retu) {
                    if (retu.order_id) {
                        helper.myAlert("修改成功！ ");
                        $scope.ordergetone(retu.order_id);
                    } else {
                        helper.myAlert("error " + retu.Msg);
                    }
                });
            }
        }

        //推送定单
        $scope.postOrder = function(id, type, stype) {
            return dataService.postOrder(id, type).then(function(retu) {
                if (retu.Msg) {
                    if (!stype) {
                        helper.message(retu.Msg, "error", 60);
                    }
                } else {
                    if (!stype) {
                        helper.message("推送成功");
                    }
                }
                return retu;
            });
        }

        //推送支付单
        $scope.postPay = function(id, stype) {
            return dataService.postPay(id).then(function(retu) {
                if (retu.Msg) {
                    if (!stype) {
                        helper.message(retu.Msg, "error", 60);
                    }
                } else {
                    if (!stype) {
                        helper.myAlert("success", null, null, function() {
                            // $scope.getorderList();
                        });
                    }
                }
                return retu;
            });
        }

        //推送
        $scope.postWms = function(id) {
            dataService.postOederWms(id).then(function(retu) {
                //console.error("retu", retu);
                if (retu.Msg) {
                    helper.message(retu.Msg, "error", 60);
                } else {
                    helper.myAlert("success", null, null, function() {
                        $scope.getorderList();
                    });
                }
            });
        }

        $scope.uncheckAll = function() {
            $scope.fhmoder = [];
        };

        $scope.checkAll = function() {
            if ($scope.idtype) {
                $scope.fhmoder = angular.copy($scope.orderslist);
                $scope.idtype = 0;
            } else {
                $scope.fhmoder = [];
                $scope.idtype = 1;
            }
        };

        //显示
        $scope.infoAction = function() {
            var id = $location.search().order_id;
            $scope.industryCode = $rootScope.industryCode;
            $scope.orderid = id;
            if (id) {
                $scope.ordergetone($scope.orderid);
            } else {
                helper.myAlert("No data found", null, null, function() {
                    $state.go("order.list");
                });
            }
        }

        $scope.ordergetone = function(id, ttl) {
            $timeout(function() {
                $scope.getorder(id);
                // $scope.getorderextinfo(id);
                $scope.getcustomsnotifys(id, ttl);
                //评价
                $scope.reviewGet(id);
            });
        }

        //订单详情
        $scope.getorder = function(id) {
            dataService.orderOne(id).then(function(one) {
                if (one) {
                    //sku显示
                    var items = one.items;
                    async.map(items, function(item, cb) {
                            var properties = item.sku_properties;
                            var a = properties.split(";");
                            var c = "";
                            for (var j in a) {
                                if (a[j]) {
                                    var b = a[j].split(":");
                                    var d = b[2] + ":" + b[3];
                                    c = d + ";" + c;
                                }
                            }
                            item.sku_name = c;
                            if (item.act_json) {
                                item.act_json = JSON.parse(item.act_json);
                            }
                            console.error("iitem", item);
                            if (item.activity_id) {
                                var query = {
                                    "query": {
                                        "activity_id": item.activity_id
                                    }
                                };

                                dataService.dazheGet(query).then(function(result) {
                                    if (result.total_count) {
                                        item.activitys = result.activitys[0];
                                        if (!item.activitys.store_id) {
                                            item.activitys.store_id = $rootScope.store_id;
                                        }

                                        cb(null, item)
                                    } else {
                                        cb(null, item)
                                    }
                                });
                            } else if (item.pintuan_id) {
                                var query = {
                                    content: {
                                        pintuan_id: item.pintuan_id,
                                        store_id: $rootScope.store_id,
                                        // item_id: $rootScope.store_id,
                                        // sku_id: $rootScope.store_id,
                                    }
                                };

                                // console.error("$rootScope", $rootScope);
                                dataService.pintuanGet(query).then(function(result) {
                                    if (result.pintuan_list) {
                                        item.pintuan_data = result.pintuan_list[0];
                                        item.pintuan_data.original_price = Number(item.pintuan_data.original_price);
                                        item.pintuan_data.pin_price = Number(item.pintuan_data.pin_price);
                                        item.pintuan_data.need_customer_num = Number(item.pintuan_data.need_customer_num);
                                        item.pintuan_data.expiration_hour = item.pintuan_data.expiration_hour ? item.pintuan_data.expiration_hour : "1";
                                        item.oldsku_price = item.pintuan_data.original_price;
                                        cb(null, item)
                                    } else {
                                        cb(null, item)
                                    }

                                });
                            } else {
                                cb(null, item)
                            }
                        }, function(e, r) {
                            one.items = r;
                            one.fuhao = $scope.huobi(one.app_id);
                            $scope.order = one;

                            //自定义表单字段获取
                            $scope.orderFormGet(one.deliver_address, items[0].xtype);
                            $scope.getorderextinfo(one.order_id);
                        })
                        // for (var i in items) {
                        //     var properties = items[i].sku_properties;
                        //     var a = properties.split(";");
                        //     var c = "";
                        //     for (var j in a) {
                        //         if (a[j]) {
                        //             var b = a[j].split(":");
                        //             var d = b[2] + ":" + b[3];
                        //             c = d + ";" + c;
                        //         }
                        //     }
                        //     items[i].sku_name = c;
                        //     if (items[i].act_json) {
                        //         items[i].act_json = JSON.parse(items[i].act_json);
                        //     }
                        // }


                } else {
                    helper.myAlert("No data found", null, null, function() {
                        $state.go("order.list");
                    });
                }
            });
        }

        $scope.getcustomsnotifys = function(id, ttl) {
            var query = {
                order_id: id
            };
            dataService.getCustomsnotifys(query, ttl).then(function(result) {
                if (result.order_data) {
                    $scope.customs_notifys = result.order_data;
                }
            });
        }

        //评价
        $scope.reviewGet = function(id) {
            var query = {
                query: {
                    order_id: id
                }
            };
            dataService.reviewGet(query).then(function(result) {
                if (result.review) {
                    $scope.review = result.review;
                }
            });
        }

        //自定义表单最新字段
        $scope.orderFormGet = function(deliver_address, xtype) {
            var data = {
                "store_id": $rootScope.store_id,
            };

            if (xtype != 0) {
                if (!deliver_address) {
                    data["type"] = "pickpoint" + xtype;
                } else {
                    data["type"] = "order" + xtype;
                }
            } else {
                if (!deliver_address) {
                    data["type"] = "pickpoint";
                } else {
                    data["type"] = "order";
                }
            }

            console.error("data type", data);

            dataService.formGet(data).then(function(data) {
                if (data.Msg == "ok") {
                    $scope.form_options = data.form_options;
                    for (var i in $scope.form_options) {
                        // $scope.form_id = $scope.form_options[i].form_id;
                        if ($scope.form_options[i].type == "remark" && $scope.form_options[i].default_value) {
                            $scope.form_options[i].default_value = json2html(JSON.parse($scope.form_options[i].default_value));
                        }
                    }
                }
            });
        }

        //订单附加信息
        $scope.getorderextinfo = function(id) {
            var query = {
                store_id: $rootScope.store_id,
                order_id: id
            };
            dataService.formDataGet(query).then(function(data) {
                if (data.total_count) {
                    $scope.data_id = data.customform_data[0].data_id;
                    $scope.order_id = id;
                    var a = data.customform_data[0].form_data;
                    var title = [];
                    var b = [];
                    for (var i in a) {
                        if (a[i].type == "area") {
                            var option = a[i].option;
                            a[i].option = option;
                            // a[i].option = option.join(" ");
                        }
                        if (a[i].type == "radio") {
                            var option1 = a[i].option;
                            var options1 = a[i].options;
                            for (var j in options1) {
                                if (options1[j].option_value == option1) {
                                    a[i].option = options1[j].option_name;
                                }
                            }
                        }
                        if (a[i].type == "checkbox") {
                            var option2 = a[i].option;
                            var options2 = a[i].options;

                            a[i].option = "";
                            for (var j in options2) {
                                if (option2.indexOf(options2[j].option_value) > -1) {
                                    a[i].option += options2[j].option_name + " ";
                                }
                            }
                        }

                        b[a[i].type_id] = a[i];

                        title.push(a[i].title);
                    }

                    $scope.form_data = a;
                    $scope.form_data1 = b;
                    //console.error("form_data1---------", $scope.form_data1);
                    $scope.title = title;
                } else {
                    $scope.form_data1 = [];
                }
            });
        }

        $scope.newExt = function(order) {
            //console.error("form_data1", $scope.form_data1);
            // return false;
            var a = [];
            var b = {};
            for (var i in $scope.form_data1) {
                a.push($scope.form_data1[i]);
                for (var j in $scope.form_options) {
                    if ($scope.form_options[j].type_id == i && !$scope.form_data1[i].type_id) {

                        if ($scope.form_options[j].type == "remark" || $scope.form_options[j].type == "hide") {
                            if ($scope.form_data1[i].option) {
                                $scope.form_data1[i].option = JSON.stringify(
                                    html2json($scope.form_data1[i].option)
                                );
                            }
                        }

                        var b = {
                            "type_id": i,
                            "type": $scope.form_options[j].type,
                            "title": $scope.form_options[j].title,
                            "title_msg": $scope.form_options[j].title_msg,
                            "options": $scope.form_options[j].options,
                            "option": $scope.form_data1[i].option,
                        }
                        a.push(b);
                    }
                }
            }
            var c = [];
            for (var m in a) {
                if (a[m].type_id) {
                    c.push(a[m]);
                }
            }

            if ($scope.data_id) {
                var data = {
                    "data_id": $scope.data_id,
                    "order_id": $scope.order_id,
                    "form_data": c
                };

                //console.error("update data", order, data);

                dataService.formDataUpdate(data).then(function(result) {
                    if (result.Msg == "ok") {
                        $scope.getorderextinfo($scope.order_id);
                    } else {
                        helper.myAlert("error:" + result.Msg);
                        return false;
                    }
                });
            } else {
                if (order.deliver_address) {
                    var type = "order";
                } else {
                    var type = "pickpoint";
                }

                var data = {
                    "order_id": order.order_id,
                    "type": type,
                    "store_id": $rootScope.store_id,
                    "member_id": order.member_id,
                    "form_data": c
                };

                //console.error("add data", order, data);
                dataService.formDataAdd(data).then(function(result) {
                    if (result.Msg == "ok") {
                        $scope.getorderextinfo(order.order_id);
                    } else {
                        helper.myAlert("error:" + result.Msg);
                        return false;
                    }
                });
            }
        }

        //订单发货
        $scope.deliveryAction = function() {
            var id = $location.search().order_id;
            if (id) {
                dataService.orderOne(id).then(function(one) {
                    if (one) {
                        one.shipping_code = Number(one.shipping_code);
                        $scope.order = one;
                        if (one.status != 'S_ORDER_WAIT_RECEIVE') {
                            $scope.order.shipping_corp = sessionService.get("shipping_corp");
                        }
                    } else {
                        helper.myAlert("No data found", null, null, function() {
                            $state.go("order.list");
                        });
                    }
                });
            } else {
                helper.myAlert("No data found", null, null, function() {
                    $state.go("order.list");
                });
            }
        }

        $scope.getdtb = function(order_id) {
            return dataService.getdtb(order_id).then(function(result) {
                $scope.datoubi = result.datoubi.data + " " + result.datoubi.extended;
            });
        }

        //订单确认
        $scope.statusup = function(order_id, event_id, $event, order, ss) {
            if (order_id && event_id) {
                var query = {
                    order_id: order_id,
                    event: $scope.Event[event_id],
                    client: 'windows'
                };
                if (event_id == 3) {
                    if (order.items[0].pintuan_activity_id && order.order_type == 4) {
                        var query1 = {
                            content: {
                                pintuan_activity_id: order.items[0].pintuan_activity_id,
                                store_id: $rootScope.store_id,
                            }
                        };
                        //是否为拼团订单
                        return $scope.pintuanup(query1, $event, query, ss);
                    } else {
                        return upDate($event, query, ss);
                    }

                } else {
                    upDate($event, query, ss);
                }
            } else {
                helper.myAlert("No order_id found");
            }
        }

        //拼团订单修改状态
        $scope.pintuanup = function(query1, $event, query, ss) {
            return dataService.pintuanactivityGet(query1).then(function(result) {
                if (result.pintuanactivity_list[0]) {
                    var pintundata = result.pintuanactivity_list[0];
                    if (pintundata.need_customer_num !== pintundata.current_customer_num) {
                        if (ss) {
                            return upDate($event, query, ss);
                        } else {
                            helper.myConfirm('此订单为拼团订单，还没有成团，您确定确认订单吗？', function() {
                                upDate($event, query, ss);
                            });
                        }
                    } else {
                        return upDate($event, query, ss);
                    }
                } else {
                    return upDate($event, query, ss);
                }
            });
        }

        function upDate($event, query, ss) {
            return dataService.orderConfirmUpdate(query).then(function(retu) {
                if (retu.order_id) {
                    if ($event) {
                        helper.myTip("success", $event.currentTarget, null, 5, function() {
                            $scope.getorderList();
                        });
                    }
                    return retu;
                    // if (ss) $scope.getorderList();

                } else {
                    helper.myAlert("error ");
                }
            });
        }


        $scope.orderCancelUpdate = function(order_id, $event) {
            var query = {
                order_id: order_id
            };
            dataService.orderCancelUpdate(query).then(function(retu) {
                if (retu.order_id) {
                    if ($event) {
                        helper.myAlert("success", null, null, function() {
                            $state.go("order.list");
                        });
                    }
                } else {
                    helper.myAlert("error ");
                }
            });
        }

        //修改订单数据
        $scope.updateOrder = function(status) {

            var title = '您确认物流发货？';
            if (status == 1) {
                title = "您确认使用无物流发货？";
            }

            helper.myConfirm(title, function() {
                if (status == 1) {
                    $scope.order.shipping_code = 0;
                    $scope.order.shipping_corp = 'SJWL';
                }
                //把物流公司加入缓存 
                sessionService.put("shipping_corp", $scope.order.shipping_corp);
                $scope.savefh(1);
            });
        }

        $scope.savefh = function(type) {
            var order = {
                order_id: $scope.order.order_id,
                shipping_corp: $scope.order.shipping_corp,
                shipping_code: $scope.order.shipping_code
            };
            return dataService.orderUpdate(order).then(function(retu) {
                if (retu.order_id) {
                    var query = {
                        order_id: retu.order_id,
                        event: $scope.Event[4],
                        client: 'windows'
                    };
                    if ($scope.order.status == 'S_ORDER_WAIT_RECEIVE') {
                        if (type) {
                            // if (t == 10) $scope.getorderList(1);
                            helper.myAlert("success", null, null, function() {
                                $state.go("order.list");
                            });
                        } else {
                            return retu;
                        }
                    } else {
                        return dataService.orderDeliveryUpdate(query).then(function(retu) {
                            if (retu.order_id) {
                                if (type) {
                                    // if (t == 10) $scope.getorderList(1);
                                    helper.myAlert("success", null, null, function() {
                                        $state.go("order.list");
                                    });
                                } else {
                                    return retu;
                                }
                            } else {
                                helper.myAlert("error ");
                            }
                        });
                    }
                } else {
                    helper.myAlert("error " + retu.Msg);
                }
            });
        }

        //发货点修改回调方法
        $scope.backpickpoint = function(pickpoint) {
            if (pickpoint) {
                var data = {
                    "content": pickpoint
                };

                dataService.orderPickpointUpdate(data).then(function(result) {
                    if (result.Msg == "ok") {
                        $scope.pickpoint_id = pickpoint.pickpoint_id;
                        helper.myAlert("success");
                        $scope.getorderList();
                    } else {
                        helper.myAlert("error：" + result.Msg);
                        return false;
                    }
                });
            }
        }

        //订单打标回调
        $scope.upflagback = function() {
            $scope.getorderList();
        }

        $scope.manualorderAction = function() {
            $scope.manualOrderData = {};
        }

        // 全选
        $scope.quickCheckAll = function() {
            $scope.sjmodel = angular.copy($scope.quickorderslist);
        }

        // 反选
        $scope.quickNoCheckAll = function() {
            if ($scope.sjmodel) {
                //循环
                var noData = [];
                var itemList = clone($scope.quickorderslist);
                for (var i = 0; i < $scope.sjmodel.length; i++) {
                    for (var j = 0; j < itemList.length; j++) {
                        if (itemList[j]) {
                            if ($scope.sjmodel[i].quick_order_id == itemList[j].quick_order_id) {
                                // delete itemList[j];
                                itemList.splice(j, 1);
                            }
                        }
                    }
                }
                $scope.sjmodel = itemList;
            } else {
                $scope.sjmodel = [];
            }
        };

        //批量删除订单
        $scope.delAllOrder = function() {
            helper.myConfirm('确定删除订单么？', function() {
                async.mapSeries($scope.sjmodel,
                    function(one, callback) {
                        dataService.delQuickOrder({
                            'scene': one.scene,
                            'store_id': $rootScope.store_id
                        }).then(function(result) {
                            if (result.Msg == "ok") {
                                callback(null, null);
                            } else {
                                callback(null, null);
                            }
                        });
                    },
                    function(e, r) {
                        helper.myAlert("success", null, null, function() {
                            $scope.getquickorderList();
                            $scope.sjmodel = [];
                        });
                    }
                );
            });
        };

        /** 
         * 手工下单 选择商品 填写收货信息
         */
        //选择商品
        // $scope.checked_item = [];
        $scope.itemdata = function(items) {
            if (items) {
                $scope.checked_item = items;
                console.error("checked_item", $scope.checked_item);
                $scope.checked_item.map(function(item) {
                    item.num = 1;
                })
            }
        }

        //移除选中的商品
        $scope.deleteSkuItem = function(index) {
            $scope.checked_item.splice(index, 1);
        }

        //检查商品数量是否填写
        $scope.checkSkuNum = function() {
            for (var i in $scope.checked_item) {
                var son = $scope.checked_item[i];
                if (!son.num || son.num == 0) {
                    helper.myAlert("数量没有设置或者设置为0，返回上一步填写！");
                    break;
                }
            }
        }

        //省份级联选择
        $scope.getCity = function(data) {
            // $scope.cityData = data;
            if (data && data[0] && data[0].id && data[1] && data[1].id && data[2] && data[2].id) {
                $scope.addressData.province = data[0].name;
                $scope.addressData.city_id = data[1].id;
                $scope.addressData.city = data[1].name;
                $scope.addressData.district_id = data[2].id;
                $scope.addressData.district = data[2].name;
            }
        }

        //手工订单保存
        $scope.manualorderAdd = function() {
            // console.error("addressData", $scope.addressData);
            //判断商品数量是否为空
            var a = [];
            for (var i in $scope.checked_item) {
                var son = $scope.checked_item[i];
                if (!son.num || son.num == 0) {
                    helper.myAlert("数量没有设置或者设置为0，不能保存，请返回第一步设置商品数量");
                    break;
                } else {
                    a.push({
                        "partner_id": son.partner_id,
                        "item_id": son.item_id,
                        "sku_id": son.sku_id,
                        "sku_properties": son.sku_properties,
                        "sku_price": son.sku_price,
                        "num": son.num
                    });
                }
            }
            //商品数据
            $scope.manualOrderData.item_data = a;

            /** 
             * 判断收货信息
             * */
            //收货人名称
            if (!$scope.addressData.real_name) {
                helper.myAlert("收货人名称不能为空！");
                return false;
            }
            //电话
            if (!$scope.addressData.mobile) {
                helper.myAlert("电话不能为空！");
                return false;
            }
            //地区
            if (!$scope.addressData.province || !$scope.addressData.city || !$scope.addressData.district) {
                helper.myAlert("地区不能为空，请选择！");
                return false;
            }
            //地址
            if (!$scope.addressData.address) {
                helper.myAlert("详细地址不能为空！");
                return false;
            }

            //身份证号和姓名
            if (!$scope.idcardData.id_name) {
                helper.myAlert("身份证姓名不能为空！");
                return false;
            }
            if (!$scope.idcardData.idcard) {
                helper.myAlert("身份证号码不能为空！");
                return false;
            }

            $scope.manualOrderData.idcard_data = $scope.idcardData;
            $scope.manualOrderData.address_data = $scope.addressData;
            $scope.manualOrderData.store_id = $rootScope.store_id;
            console.error("manualOrderData", $scope.manualOrderData);

            // $scope.ks_order_id = "KSXD123123123124324";
            // return false;
            dataService.manualOrderAdd($scope.manualOrderData).then(function(result) {
                if (result.Msg == "ok") {
                    $scope.ks_order_id = result.ks_order_id;
                } else {
                    helper.myAlert("error：" + result.Msg);
                    return false;
                }
            });
        }

        //生成小程序码
        $scope.wxaacallback = function(app_id) {
            if (!app_id) {
                app_id = $scope.wxappid;
            }
            if ($scope.ks_order_id) {
                $scope.openQrcode(app_id);
            }
        }

        //弹出小程序二维码
        $scope.openQrcode = function(app_id) {
            dataService.acodeunlimitGet(
                app_id,
                $scope.ks_order_id,
                true,
                "pages/index/index"
            ).then(function(image) {
                console.error("二维码数据：", image);
                if (!image) {
                    //$scope.authUrl();
                    helper.myAlert("出错了！");
                    return false;
                }

                $.alert({
                    backdrop: "static",
                    keyboard: false,
                    title: "<span>小程序二维码，请使用微信扫描</span>",
                    body: '<div style="text-align:center;"><img src="data:image/png;base64,' +
                        image +
                        '"  width="240"/></div>',
                    okBtn: '{{"二维码"|translate}}',
                    closeBtn: true,
                    hasfoot: false,
                    transition: true,
                    width: "small",
                    show: function(e) {},
                    okHide: function(e) {},
                    shown: function(e) {}
                });
            });
        };

        $scope.memberdata1 = function(memberInfo) {
            $scope.member_id = memberInfo.member_id;
        };

        // 查询货币
        $scope.huobi = function(app_id) {
            var fuhao = "￥";
            if ($rootScope.huilvfuhao && $rootScope.huilvfuhao[app_id]) {
                if ($rootScope.huilvfuhao[app_id][$scope.store_id] && $rootScope.huilvfuhao[app_id][$scope.store_id][0]) {
                    fuhao = $rootScope.huilvfuhao[app_id][$scope.store_id][0].name;
                } else {
                    fuhao = "￥";
                }
            }
            return fuhao
        }

        // 快速下单列表
        $scope.manualorderlistAction = function() {
            $scope.pageSize = 10;
            $scope.getquickorderList();
            $scope.$on('event:up-store-id', function() {
                $scope.store_id = $rootScope.store_id;
                $scope.getquickorderList();
            });
        }

        $scope.getquickorderList = function(pageNo) {
            var query = {
                page_no: pageNo,
                page_size: $scope.pageSize,
                store_id: $rootScope.store_id,
            };

            $scope.quickorderslist = [];
            $scope.quickorderTotal = 0;
            dataService.quickorderList(query).then(function(list) {
                $timeout(function() {
                    if (list) {
                        $scope.quickorderslist = list.quick_order_list;
                        $scope.quickorderTotal = list.total_count;
                    }
                });
            });
        }

        //快速下单 导入订单
        $scope.manualorderimportAction = function() {
            $scope.mb = ERP_CONFIG.webUrl + '/web/dhfshop/app/images/example.xls';
        }

        //文件导入
        $scope.fileUpload = function(file, token) {
            if (!file) {
                helper.myAlert("请选择导入文件！");
                return false;
            }
            var filename = file.name.split('.');
            var hz = filename[filename.length - 1];
            if (hz !== 'xls') {
                helper.myAlert("导入模板文件不是xls");
                return false;
            }

            var token = sessionService.get('token');

            file.upload = Upload.upload({
                url: ERP_CONFIG.api2Url + '/api2/rest/',
                data: {
                    method: 'dhf.quickorder.manualorderimport',
                    file: file,
                    store_id: $rootScope.store_id,
                    token: token
                }
            });
            // return false;
            file.upload.then(function(response) {
                $timeout(function() {
                    console.error("response", response);
                    // return false;
                    file.result = response.data;
                    if (file.result.Msg == "ok") {
                        // helper.myAlert("success");
                        // $scope.getquickorderList();

                        helper.myAlert("success", null, null, function() {
                            $state.go("order.manualorderlist");
                        });

                    } else {
                        helper.myAlert("error" + file.result.Msg);
                    }
                });
            }, function(response) {}, function(evt) {});
        }

        //首页点击生成二维码
        $scope.wxcallback = function(ks_order_id) {
            if (ks_order_id) {
                $scope.ks_order_id = ks_order_id;
                $scope.openQrcode($scope.wxappid);
            }
        }

        //首页点击生成二维码
        $scope.pushWmsMsg = function(order_id) {
            helper.myConfirm("是否通知仓库取消订单？", function() {
                if (order_id) {
                    var query = {
                        order_id: order_id,
                        store_id: $rootScope.store_id,
                    };
                    dataService.pushWmsMsg(query).then(function(result) {
                        if (result.Msg == "ok") {
                            helper.myAlert("success");
                            $scope.getquickorderList();
                        } else {
                            helper.myAlert("error：" + result.Msg);
                            return false;
                        }
                    });
                }
            })
        }

        //补推清单
        $scope.pushClearOrder = function(order_id) {
            helper.myConfirm("确定补推清单信息吗？", function() {
                if (order_id) {
                    var query = {
                        order_id: order_id,
                        store_id: $rootScope.store_id,
                    };
                    dataService.pushClearOrder(query).then(function(result) {
                        if (result.Msg == "ok") {
                            helper.myAlert("success");
                            $scope.getquickorderList();
                        } else {
                            helper.myAlert("error：" + result.Msg);
                            return false;
                        }
                    });
                }
            })
        }

        //删除快速订单
        $scope.delQuickOrder = function(scene) {
            helper.myConfirm('确定删除订单么？', function() {
                dataService.delQuickOrder({
                    'scene': scene,
                    'store_id': $rootScope.store_id
                }).then(function(result) {
                    if (result.Msg == "ok") {
                        helper.myAlert("success");
                        $scope.getquickorderList();
                    } else {
                        helper.myAlert("error：" + result.Msg);
                        return false;
                    }
                });
            });
        }
    }
})();